package com.wnhz.work.yz.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.TimePickerView;
import com.google.gson.Gson;
import com.wnhz.work.yz.BaseActivity;
import com.wnhz.work.yz.MyApplication;
import com.wnhz.work.yz.R;
import com.wnhz.work.yz.base.BaseRVAdapter;
import com.wnhz.work.yz.base.BaseViewHolder;
import com.wnhz.work.yz.bean.Finish1;
import com.wnhz.work.yz.bean.GoToOrderBean;
import com.wnhz.work.yz.bean.Install2Bean;
import com.wnhz.work.yz.bean.JsonBean;
import com.wnhz.work.yz.utils.GetJsonDataUtil;
import com.wnhz.work.yz.utils.Url;
import com.wnhz.work.yz.utils.xutils3.MyCallBack;
import com.wnhz.work.yz.utils.xutils3.XUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.x;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class Details1ToPayActivity extends BaseActivity implements View.OnClickListener {
    private RecyclerView recycler;
    private ArrayList<Install2Bean.InfoEntity.ListEntity> list = new ArrayList<>();

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(Finish1 event) {
        finish();
    }


    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);//反注册EventBus
        super.onDestroy();
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_details1_to_pay);
        EventBus.getDefault().register(this);
        initJsonData();
        list = (ArrayList<Install2Bean.InfoEntity.ListEntity>) getIntent().getSerializableExtra("list");
        initTitle();
        initView();
    }

    private EditText realname, tel, remark, address2;
    private TextView address, time;

    private void initView() {
        tel = (EditText) findViewById(R.id.tel);
        remark = (EditText) findViewById(R.id.remark);
        realname = (EditText) findViewById(R.id.name);
        address2 = (EditText) findViewById(R.id.address2);
        address = (TextView) findViewById(R.id.address);
        time = (TextView) findViewById(R.id.time);
        findViewById(R.id.chengshi).setOnClickListener(this);
        findViewById(R.id.ll_time).setOnClickListener(this);
        ///
        recycler = (RecyclerView) findViewById(R.id.recycler);
        recycler.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        recycler.setAdapter(new BaseRVAdapter(this, list) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_install_detail1_222;
            }

            @Override
            public void onBind(BaseViewHolder holder, int position) {
                x.image().bind(holder.getImageView(R.id.img), list.get(position).getGoods_img());
                holder.setTextView(R.id.num, "×" + list.get(position).getNum());
                holder.setTextView(R.id.text_title, list.get(position).getGoods_name());
                holder.setTextView(R.id.text_desc, list.get(position).getGoods_des());
                holder.setTextView(R.id.text_price, list.get(position).getPrice());
            }

        });
    }

    private void initTitle() {
        TextView title = (TextView) findViewById(R.id.view_main_middle_title);
        title.setText("结算");
        findViewById(R.id.btn_main_left).setOnClickListener(this);
        TextView submit = (TextView) findViewById(R.id.submit);
        submit.setText("下一步");
        submit.setVisibility(View.VISIBLE);
        submit.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_main_left:
                finish();
                break;
            case R.id.chengshi:
                ShowPickerView();
                break;
            case R.id.ll_time:
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                Date curDate = new Date(System.currentTimeMillis());//获取当前时间
                String str = formatter.format(curDate);
                String[] b = str.split("-");
                Calendar startDate = Calendar.getInstance();
                startDate.set(Integer.parseInt(b[0]), Integer.parseInt(b[1]) - 1, Integer.parseInt(b[2]));
                Calendar endDate = Calendar.getInstance();
                endDate.set(2110, 10, 29);
                TimePickerView pvTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {//选中事件回调

                        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                        String defaultTime = format.format(date);

                        time.setText(defaultTime);
                    }
                })
                        .setTitleBgColor(Color.WHITE)//标题背景颜色 Night mode
                        .setTitleColor(getResources().getColor(R.color.text))//标题文字颜色)//标题文字颜色
                        .setSubmitColor(getResources().getColor(R.color.main_color))//确定按钮文字颜色
                        .setCancelColor(getResources().getColor(R.color.main_color))//取消按钮文字颜色
                        .setType(TimePickerView.Type.YEAR_MONTH_DAY_HOUR_MIN)//默认全部显示
                        .setOutSideCancelable(false)//点击屏幕，点在控件外部范围时，是否取消显示
                        .setTitleBgColor(getResources().getColor(R.color.white))//标题背景颜色 Night mode
                        .setBgColor(getResources().getColor(R.color.white))//滚轮背景颜色 Night mode
                        .setRangDate(startDate, endDate)//默认是1960-2110年
                        .setDate(startDate)// 默认是系统时间*/
                        .build();
                pvTime.show();
                break;
            case R.id.submit:
                //startActivity(new Intent(this, GotoOrderActivity.class).putExtra("info1", info1));

                if ("".equals(realname.getText().toString().trim())) {
                    MyToast("请填写您的姓名");
                    return;
                }
                if ("".equals(address.getText().toString().trim())) {
                    MyToast("请选择您的所在城市");
                    return;
                }

                if ("".equals(tel.getText().toString().trim())) {
                    MyToast("请填写您的手机号");
                    return;
                }


                upYuYue();


                break;
        }
    }


    private void upYuYue() {
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getUserBean().getToken());

        map.put("realname", realname.getText());
        map.put("tel", tel.getText());
        map.put("pid", getIntent().getStringExtra("pid"));
        map.put("type", getIntent().getStringExtra("type"));
        map.put("province", province1);
        map.put("city", city1);
        map.put("district", district1);
        if (!"".equals(address2.getText()))
            map.put("address", address2.getText());
        if (!"".equals(time.getText()))
            map.put("service_time", time.getText());
        if (!"".equals(remark.getText()))
            map.put("remark", remark.getText());
        Double total = 0d;
        for (int n = 0; n < list.size(); n++) {
            total += Double.parseDouble(list.get(n).getPrice()) * Double.parseDouble(list.get(n).getNum());
        }
        DecimalFormat df = new DecimalFormat("######0.00");
        map.put("amount", "0");

        StringBuffer sb = new StringBuffer("[");
        if (list != null) {
            for (int i = 0; i < list.size(); i++) {
                sb.append("{\n" +
                        "            \"type\":\"" + 2 + "\",\n" +
                        "            \"pid\":\"" + list.get(i).getGoods_id() + "\",\n" +
                        "            \"price\":\"" + list.get(i).getPrice() + "\",\n" +
                        "            \"nums\":\"" + list.get(i).getNum() + "\"\n" +
                        "        }");
                if (i != list.size() - 1) {
                    sb.append(",");
                }
            }
            sb.append("]");
            map.put("json_str", sb.toString());
        }
        showDialog();
        Set keys = map.keySet();
        if (keys != null) {
            Iterator iterator = keys.iterator();
            while (iterator.hasNext()) {
                Object key = iterator.next();
                Object value = map.get(key);
                Log.e("----" + key, "" + value + "\n");
            }
        }

        XUtil.Post(Url.DECORATE_MAKEORDER, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.i("----", "onSuccess:= " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    String info = jsonObject.optString("info");
                    if ("1".equals(res)) {
                        // MyToast(info);
                        Gson gson = new Gson();
                        GoToOrderBean bean = gson.fromJson(result, GoToOrderBean.class);
                        GoToOrderBean.InfoEntity info1 = bean.getInfo();
                        startActivity(new Intent(Details1ToPayActivity.this, GotoOrderActivity.class).putExtra("info1", info1));
                    } else {
                        if ("-1".equals(res)) {
                            info = "请重新登录";
                        }
                        MyToast(info);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                closeDialog();
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                closeDialog();
                ex.printStackTrace();
            }
        });

    }

    private String province1;
    private String city1;
    private String district1;

    private void ShowPickerView() {// 弹出选择器

        OptionsPickerView pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = options1Items.get(options1).getPickerViewText() + "-" +
                        options2Items.get(options1).get(options2) + "-" +
                        options3Items.get(options1).get(options2).get(options3);
                address.setText(tx);
                province1 = options2Items.get(options1).get(options2);
                city1 = options1Items.get(options1).getPickerViewText();
                district1 = options3Items.get(options1).get(options2).get(options3);

            }
        })

                .setTitleBgColor(Color.WHITE)//标题背景颜色 Night mode
                .setTitleColor(getResources().getColor(R.color.text))//标题文字颜色)//标题文字颜色
                .setSubmitColor(getResources().getColor(R.color.main_color))//确定按钮文字颜色
                .setCancelColor(getResources().getColor(R.color.main_color))//取消按钮文字颜色.build();
                .build();
        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        if (options1Items.size() == 0) {
            initJsonData();
            return;
        }
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }

    private ArrayList<JsonBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();

    private void initJsonData() {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = new GetJsonDataUtil().getJson(this, "province.json");//获取assets目录下的json文件数据

        ArrayList<JsonBean> jsonBean = GetJsonDataUtil.parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCityList().get(c).getName();
                CityList.add(CityName);//添加城市

                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    City_AreaList.add("");
                } else {

                    for (int d = 0; d < jsonBean.get(i).getCityList().get(c).getArea().size(); d++) {//该城市对应地区所有数据
                        String AreaName = jsonBean.get(i).getCityList().get(c).getArea().get(d);

                        City_AreaList.add(AreaName);//添加该城市所有地区数据
                    }
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }
    }

}
